import {
  Controller,
  Post,
  Get,
  Request,
  Response,
  Body,
  UseGuards,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtHttpGuard } from './jwt-http.guard';
import type { Response as ExpressResponse } from 'express';

@Controller('/api/auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('login')
  async login(
    @Body() body: { username: string; password: string },
    @Response() res: ExpressResponse,
  ) {
    const user = await this.authService.validateUser(body.username, body.password);
    if (!user) {
      return res.json({
        code: 401,
        message: '用户名或密码错误',
        data: null,
        timestamp: Date.now(),
      });
    }
    const token = await this.authService.login(user);
    
    // 设置cookie
    res.cookie('access_token', token.access_token, {
      // httpOnly: true, // 这样前端无法通过JavaScript访问cookie
      maxAge: 24 * 60 * 60 * 1000, // 24小时
    });
    
    return res.json({
      code: 0,
      message: 'success',
      data: token,
      timestamp: Date.now(),
    });
  }

  @UseGuards(JwtHttpGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}